<?php

namespace app\common\model;

use think\Cache;
use think\Db;
use think\Model;
use addons\shopro\model\UserWalletLog;

/**
 * 分销会员数据模型
 */
class RetailUser extends Model
{
    const STATUS_ENABLE     = 1;//正常
    const STATUS_DISABLE    = 2;//黑名单

    const LEVEL_FENS     = 1;//粉丝
    const LEVEL_WANKE    = 2;//玩客
    const LEVEL_WANZHU   = 3;//玩主
    const LEVEL_WANJIA   = 4;//玩家

    const UP_WANKE          = 15;//玩客晋升直属玩客数量
    const UP_WANKE_TOTAL    = 60;//玩客晋升累计玩客数量

    const UP_WANZHU         = 20;//玩主晋升直属玩客数量
    const UP_WANZHU_TOTAL   = 1000;//玩主晋升累计玩客数量
    const UP_WANZHU_ZHISHU  = 3;//玩主晋升累计玩主数量

    /**
     * 前端会员中心列表
     */
    const LIST_TYPE_TEAM    = 'team';
    const LIST_TYPE_XIAJI   = 'xiaji';
    const LIST_TYPE_ZHISHU  = 'zhishu';
    const LIST_TYPE_YUCHEN  = 'yuchen';

    const LIST_TYPE_FENS_TOTAL    = 'fens_total';//推荐关系下所有成员
    const LIST_TYPE_WANKE_TOTAL   = 'wanke_total';//推荐关系下所有玩客
    const LIST_TYPE_WANZHU_TOTAL  = 'wanzhu_total';//推荐关系下所有玩主
    const LIST_TYPE_WANJIA_TOTAL  = 'wanjia_total';//推荐关系下所有玩加

    const LIST_SELECT_FIELD = "u.id,ru.level,ru.total_income,u.username as user_name,u.nickname as nickname,u.avatar,u.mobile,ru.pid,IF(`pid` = %s,1,0) as is_child";

    /**
     * 获取会员信息
     */
    public function getUserInfo($user_id)
    {
        $retailUser = db('retail_user')
            ->field('ru.*,u.id,u.username as user_name,u.nickname as nickname,u.mobile')
            ->alias('ru')
            ->join('user u','u.id = ru.uid')
            ->find($user_id);

        if(!empty($retailUser)){
            switch($retailUser['level']){
                case RetailUser::LEVEL_WANKE:
                    $retailUser['level_name'] = "玩客";
                    break;
                case RetailUser::LEVEL_WANZHU:
                    $retailUser['level_name'] = "玩主";
                    break;
                case RetailUser::LEVEL_WANJIA:
                    $retailUser['level_name'] = "玩家";
                    break;
                default:
                    $retailUser['level_name'] = "粉丝";
                    break;
            }
        }

        return $retailUser;
    }

    /**
     *  奖金池添加N元,收纳记录表记录一条数据
     */
    public static function insReward($user)
    {
        $month = date('Ym');

        $one_money = db('config')->where(['name'=>'each_wanke_reward'])->value('value');
        $one_money = $one_money ?? 20;

        //奖金池
        $reward = db('retail_reward')->where(['month'=>$month])->find();
        if(empty($reward)){
            //插入这个月第一条奖金
            $data = [
                'month' => $month,
                'total' => $one_money,
            ];
            db('retail_reward')->insert($data);
            $reward['id'] = db('retail_reward')->getLastInsID();

            $total = $one_money;
        }else{
            $total = $reward['total'] + $one_money;
            db('retail_reward')->where(['id'=>$reward['id']])->update(['total'=>$total]);
        }

        //玩客总数量
        $count = db('retail_user')->where(['level'=>['egt',RetailUser::LEVEL_WANKE]])->count();

        //收纳记录
        $logData = [
            'user_id'   => $user['uid'],
            'reward_id' => $reward['id'],
            'nickname' => $user['nickname'],
            'money'     => $one_money,
            'total_money' => $total,
            'total_wanke' => $count,//第几个玩客
            'create_time' => time(),
        ];

        db('retail_reward_log')->insert($logData);

    }

    public function user()
    {
        return $this->belongsTo('User', 'uid', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * 获取团队成员数量
     */
    public function teamPersonCount($user)
    {
        $user_id    = $user['id'];
        $level      = $user['level'];
        $teamids[]  = $user_id;
        while ($level > 1){
            //找到直属下级
            $level--;

            $children = db('retail_user')->where(['level'=>$level,'pid'=>['in',$teamids]])->column('uid');
            $teamids = array_merge($teamids,$children);
        }
        return count($teamids);
    }

    /**
     * 获取团队成员
     */
    public function teamPersonList($user,$ret_team_ids = false)
    {
        $user_id    = $user['id'];
        $level      = $user['level'];
        $teamids[]  = $user_id;
        while ($level > 1){
            //找到直属下级
            $level--;

            $children = db('retail_user')->where(['level'=>$level,'pid'=>['in',$teamids]])->column('uid');
            $teamids = array_merge($teamids,$children);
        }

        if($ret_team_ids){
            //只返回团员ID集合
            return $teamids;
        }

        $data = db('retail_user')
            ->field(self::LIST_SELECT_FIELD)
            ->alias('ru')
            ->join('user u','u.id = ru.uid','left')
            ->where(['ru.uid'=>['in',$teamids]])
            ->order('ru.level desc')
            ->select();
        return $data;
    }

    /**
     * 下一级列表
     * @param $user
     */
    public function xiajiPersonList($user)
    {
        $user_id    = $user['id'];
        $level      = $user['level'];

        $all_ids    = [];//所有大于等于玩客等级的ID集合
        $data       = [];

        if($level == self::LEVEL_WANZHU){
            $xiaji_level = self::LEVEL_WANKE;
        }elseif($level == self::LEVEL_WANJIA){
            $xiaji_level = self::LEVEL_WANZHU;
        }else{
            return [];
        }

        $children = db('retail_user')->where(['level'=>['EGT',$xiaji_level],'pid'=>$user_id])->column('uid');
        if (empty($children)){
            return [];
        }

        while (!empty($children)){
            $all_ids    = array_merge($all_ids,$children);
            $children   = db('retail_user')->where(['level'=>['EGT',$xiaji_level],'pid'=>['in',$children]])->column('uid');
        }

        $data = db('retail_user')
            ->field(self::LIST_SELECT_FIELD)
            ->alias('ru')
            ->join('user u','u.id = ru.uid','left')
            ->where(['ru.level'=>$xiaji_level,'uid'=>['in',$all_ids]])
            ->order('ru.level desc')
            ->select();

        return $data;

    }

    /**
     * 直系成员列表
     */
    public function zhisuPersonList($user)
    {
        $user_id    = $user['id'];
        $level      = $user['level'];

        $w = [
            //'level'=>['LT',$level],
            'pid'=> $user_id
        ];

        $yuchen = db('retail_user')
            ->field(self::LIST_SELECT_FIELD)
            ->alias('ru')
            ->join('user u','u.id = ru.uid','left')
            ->where($w)
            ->order('ru.level desc')
            ->select();

        return $yuchen;
    }

    /**
     * 育成上级列表
     */
    public function yuchenPersonLis($user)
    {
        $user_id    = $user['id'];
        $level      = $user['level'];

        $yuchen = db('retail_user')
            ->field(self::LIST_SELECT_FIELD)
            ->alias('ru')
            ->join('user u','u.id = ru.uid','left')
            ->where(['ru.level'=>['EGT',$level],'pid'=> $user_id])
            ->select();

        return $yuchen;
    }

    /**
     * 获取推荐关系下所有成员
     * @param $user 团队长
     * @param int $level 团员等级筛选
     * @param bool $ret_team_ids 直接返回ID
     * @return array
     */
    public function fensPersonList($user,$level = 0, $ret_team_ids = false)
    {
        $user_id    = $user['id'];
        $teamids  = [];
        $parentIds  = $user_id;//上级会员ID

        while (!empty($parentIds)){
            //找到下级
            $children = db('retail_user')->where(['pid'=>['in',$parentIds]])->column('uid');

            //加入团队成员ID集合
            if(!empty($children)){
                $teamids = array_merge($teamids,$children);
            }

            //为了再次查找下级的下级
            $parentIds = $children;
        }

        if($ret_team_ids && $level == 0){
            //只返回团员ID集合
            return $teamids;
        }


        $w = ['ru.uid'=>['in',$teamids]];
        if($level){
            //根据玩家等级拆分
            $w['ru.level'] = $level;
        }

        $fieldRaw = "u.id,ru.level,ru.total_income,u.username as user_name,u.nickname as nickname,u.avatar,u.mobile,ru.pid,IF(`pid` = {$user_id},1,0) as is_child,ru.fens_total";
        $data = db('retail_user')
            ->fieldRaw($fieldRaw)
            ->alias('ru')
            ->join('user u','u.id = ru.uid','left')
            ->where($w)
            ->order('is_child desc, ru.level desc')
            ->paginate(10);

        if($ret_team_ids && $level != 0){
            //只返回团员ID集合
            $teamids = [];
            foreach ($data->items() as $item){
                $teamids[] = $item['uid'];
            }
            return $teamids;
        }

        return $data;
    }

    /**
     * 团队收入分成
     *
     * @param $user 获得收入的用户ID
     * @param $money 用户获得的收入
     */
    public Static function teamReward($user,$money,$order_id,$conf = null)
    {
        if(!$conf){
            $retailConfigModel = new RetailConfig();
            $conf   = $retailConfigModel->getRecommendConfig("team");
        }
        if($money < 0.1){
            return 0;
        }

        //查询用户的上级团队
        $parent = db('retail_user')->where(['uid'=>$user['pid']])->find();
        if(empty($parent)){
            return 0;
        }

        if($parent['level'] < self::LEVEL_WANZHU){
            //继续找上级团队长
            self::teamReward($parent,$money,$order_id,$conf);
            return;

        }


        $userModel = new \addons\shopro\model\User();
        $parent_user = $userModel->find($parent['uid']);
        //开始给上级分佣
        $commission = $money * $conf[$parent['level']] / 100;
        $insData = [
            'order_id'=>$order_id,
            'child_id'=>$user['uid'],
            'user_id' => $parent['uid'],
            'commission'=>$commission,
            'create_time'=>time(),
        ];

        $WalletModel = new UserWalletLog();
        Db::startTrans();
        try{
            //方便退款
            db('retail_team_commission')->insert($insData);
            db('user')->where(['id'=>$parent['uid']])->setInc('money',$commission);
            db('retail_user')->where(['uid'=>$parent['uid']])->setInc('total_income',$commission);
            $WalletModel->doAdd($parent_user, $commission, 'sale_reward_team', 0, "money", 1);

            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            \think\log::error("用户:{$user['id']}的团队分配任务失败:".$e->getMessage());
        }

        self::teamReward($parent,$commission,$order_id,$conf);

    }

    /**
     * 修复等级关系
     * @param $ids 用户ID集合
     */
    public static function repaire($ids = [])
    {
        if(empty($ids)){
            return 0;
        }
        $users = db('retail_user')->where(['uid'=>['in',$ids]])->select();
        $retailUserModel = new RetailUser();
        foreach ($users as $item){
            $item['id'] = $item['uid'];
            $data = [
                'fens_num'      =>0,
                'wanke_num'     =>0,
                'wanzhu_num'    =>0,
                'wanjia_num'    =>0,
                'fens_total'    =>0,
                'wanke_total'   =>0,
                'wanzhu_total'  =>0,
                'wanjia_total'  =>0,
            ];

            //直属
            $data['fens_num']   = db('retail_user')->where(['pid'=>$item['uid'],'level'=>['EGT',1]])->count();
            $data['wanke_num']  = db('retail_user')->where(['pid'=>$item['uid'],'level'=>['EGT',2]])->count();
            $data['wanzhu_num'] = db('retail_user')->where(['pid'=>$item['uid'],'level'=>['EGT',3]])->count();
            $data['wanjia_num'] = db('retail_user')->where(['pid'=>$item['uid'],'level'=>['EGT',4]])->count();

            //累计
            $data['fens_total']     = count($retailUserModel->fensPersonList($item));

            $wanjia_total = count($retailUserModel->fensPersonList($item,RetailUser::LEVEL_WANJIA));
            $wanzhu_total = $wanjia_total + count($retailUserModel->fensPersonList($item,RetailUser::LEVEL_WANZHU));
            $wanke_total = $wanzhu_total + count($retailUserModel->fensPersonList($item,RetailUser::LEVEL_WANKE));
            $data['wanke_total']    = $wanke_total;
            $data['wanzhu_total']   = $wanzhu_total;
            $data['wanjia_total']   = $wanjia_total;

            db('retail_user')->where(['uid'=>$item['uid']])->update($data);
        }

        return 1;
    }

}
